package com.tanhua.sso.controller;

import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.tanhua.sso.pojo.User;
import com.tanhua.sso.service.UserService;
import com.tanhua.sso.vo.ErrorResult;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.http.ResponseEntity;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
/**
 * @description:
 * @program: mytanhua
 * @author: Leon
 * @date: 2021-01-26 22:36
 **/
@Slf4j
@RestController
@RequestMapping("user")
@SuppressWarnings("all")
public class UserController {
    @Autowired
    private UserService userService;

    /**
     * 用户登录
     * @param param
     * @return
     */
    @RequestMapping("loginVerification")
    public ResponseEntity<Object> login(@RequestBody Map<String,String> param){

        try{
            String phone = param.get("phone");
            String code = param.get("verificationCode");
            String data = userService.login(phone,code);
//        登陆成功
            if (StringUtils.isNotEmpty(data)){
                String[] split = StringUtils.split(data,"|");
                Map<String,Object> result = new HashMap<>(2);
                result.put("token",split[0]);
                result.put("isNew",Boolean.valueOf(split[1]));
                return ResponseEntity.ok(result);
            }
        }catch (Exception e){
            e.printStackTrace();
        }
        ErrorResult errorResult = ErrorResult.builder().errCode("00002").errMessage("登录失败!").build();
        return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body(errorResult);
    }

    /**
     * 校验token，根据token查询用户数据
     *
     * @param token
     * @return
     */
    @GetMapping("{token}")
    public User queryUserByToken(@PathVariable("token") String token) {
        return this.userService.queryUserByToken(token);
    }
}
